<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\Relation;
use app\common\tool\Result;
use think\facade\Db;
use think\facade\View;
use think\Response;
use think\response\Json;
use addons\Builder\facade\Builder;
use app\common\model\Assets;
use app\common\model\Level;
use app\common\model\Logs;
use think\exception\ValidateException;

class User extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\User';

    //验证器
    protected string $validate = 'User';

    //关联模型
    protected array $hasOne = ['assets', 'level'];

    protected array $append = ['parent_info'];

    //数据排序，支持多个
    protected array $sort = [
        'ordinary' => [
            'create_time' => 'desc'
        ],
        'formal' => [
            'active_time' => 'desc'
        ]
    ];

    public function ordinary(): string
    {
        return $this->fetch(['delete'], ['add' => ['size' => '50%']], ['is_active', '=', 1]);
    }

    public function formal(): string
    {
        return $this->fetch([], [], ['is_active', '=', 2], 2, 150);
    }

    public function fetch($rb = [], $tb = [], $extra_map = [], $type = 1, $width = 200): string
    {
        $table = Builder::Table()
            ->addColumn(['fixed' => 'left', 'title' => '全选', 'type' => 'checkbox'])
            ->addColumn(['field' => 'id', 'title' => 'ID', 'sort' => true, 'fixed' => 'left', 'width' => 80])
            ->addColumn(['field' => 'code', 'title' => '会员编号', 'fixed' => 'left'])
            ->addColumn(['field' => 'nickname', 'title' => '会员昵称', 'modify' => '2,input', 'fixed' => 'left'])
            ->addColumn(['field' => 'mobile', 'title' => '手机号', 'modify' => '2,number', 'fixed' => 'left'])
            ->addColumn(['field' => 'parent_code', 'title' => '邀请码', 'modify' => '1,input', 'hide' => true])
            ->addColumn(['field' => 'parent_info', 'title' => '推荐人']);
        if ($type == 1) {
            $table->addColumn(['field' => 'level_id', 'title' => '会员等级', 'templet' => '{{d.level?d.level.title:"无"}}']);
        } else {
            $table->addColumn(['field' => 'level_id', 'title' => '会员等级', 'modify' => '4,select,getLevel', 'templet' => '{{d.level?d.level.title:"无"}}']);
        }
        return $table->autoSpliceColumns(8, Assets::getFields(3), "assets", true)
            ->addColumn(['field' => 'my_total', 'title' => '个人业绩'])
            ->addColumn(['field' => 'team_total', 'title' => '团队业绩'])
            ->addColumn(['field' => 'active_time', 'title' => '激活时间'])
            ->addColumn(['field' => 'create_time', 'title' => '注册时间'])
            ->addColumn(['field' => 'is_lock', 'title' => '状态', 'modify' => '4,radio,getLock', 'templet' => '#is_lock', 'width' => 120])
            ->addColumn(['fixed' => 'right', 'title' => '操作', 'align' => 'center', 'toolbar' => '#barDemo', 'width' => $width])
            ->addSwitchTool([['name' => 'is_lock', 'pk' => $this->pk, 'text' => '锁定|正常', 'val' => '1|0', 'checked' => 1]])
            ->addExtraMap([$extra_map])
            ->addRightButtons(
                array_merge([
                    'login' => ['title' => '登录', 'url' => url('user/login')->build()],
                    'edit' => ['size' => '50%']
                ], $rb))
            ->addTopButtons(
                array_merge($tb, [
                    'reset_1' => [
                        'title' => '重置登录密码',
                        'placeholder' => '请填写新密码，默认111111',
                        'icon' => 'layui-icon-password',
                        'url' => url('user/reset', ['type' => 1])->build(),
                        'event' => '_batchPrompt'
                    ],
                    'reset_2' => [
                        'title' => '重置支付密码',
                        'placeholder' => '请填写新密码，默认222222',
                        'icon' => 'layui-icon-password',
                        'url' => url('user/reset', ['type' => 2])->build(),
                        'event' => '_batchPrompt'
                    ],
                    'export'
                ])
            )
            ->addSearch([
                ['code__nickname__mobile', '会员编号/昵称/手机号', 'input,Like'],
                ['parent_code', '推荐人编号', 'input,Like']
            ])
            ->addSearchList([
                [
                    'filed' => 'level_id',
                    'title' => '会员等级',
                    'child' => Level::field('id as value,title')->select()
                ]
            ])
            ->fetch();
    }

    public static function getLevel(): array
    {
        return array_merge([0 => '暂无'], Level::column('title', 'id'));
    }

    public static function getLock(): array
    {
        return ['正常', '锁定'];
    }

    public function save($param = [], $model = true): Json
    {
        return parent::save($this->request->post(), $model);
    }

    public function delete(): Response
    {
        Db::startTrans();
        try {
            $user = $this->model::where('id', $this->request->post($this->pk))->find();
            if (empty($user)) {
                throw new \Exception('会员不存在');
            }
            if ($user->is_active == 2) {
                throw new \Exception('会员已激活，无法删除');
            }
            $count = Relation::where(['uid' => $user->id])->count();
            if ($count) {
                throw new \Exception('该会员已推荐会员无法删除');
            }
            Relation::destroy(['new_uid' => $user->id]);
            $this->model::destroy(['id' => $user->id]);
            Logs::adds('删除会员【' . $user->id . '】【' . $user->code . '】', $this->admin->id, $this->admin->admin_name);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return Result::fail($e->getMessage());
        }

        return Result::success('已删除');
    }

    public function reset($type): Response
    {
        try {
            $ids = $this->request->post('ids');
            $pass = $this->request->post('pass');
            if ($type == 1) {
                $key = 'password';
                $value = md5($pass ?: '111111');
                $name = '登录密码';
            } else {
                $key = 'pay_password';
                $value = md5($pass ?: '222222');
                $name = '支付密码';
            }
            $this->model::update([$key => $value], ['id' => $ids]);
            $msg = '重置了【' . $name . '】会员标识ID【' . implode(',', $ids) . '】';
            Logs::adds($msg, $this->admin->id, $this->admin->admin_name);

        } catch (\Exception $e) {

            return Result::fail($e->getMessage());
        }

        return Result::success('已重置');
    }

    public function login($id): Response
    {
        try {
            $user = $this->model::find($id);
            if ($user->token) {
                $token = $user->token;
            } else {
                $token = md5(time() . json_encode($user));
                $user->token = $token;
                $user->save();
            }
            cookie('token', $token);
            $description = '登录操作，会员【' . $user->code . '】';
            Logs::adds($description, $this->admin['id'], $this->admin['admin_name']);

        } catch (\Exception $e) {

            return Result::fail($e->getMessage());
        }

        return Result::success('登录成功', ['code' => $user->code, 'url' => '/']);
    }

    public function recharge(): Response|string
    {
        $param = $this->request->param();
        if ($this->request->isAjax()) {
            switch ($param['type']) {
                case "get":
                    $user = $this->model::whereLike('code|mobile|nickname', '%' . $param['val'] . '%')
                        ->field('id,code,mobile,nickname')->select();
                    return Result::success('success', $user, 0);
                case "account":
                    $assets = Assets::where(['uid' => $param['id']])->value($param['val']);
                    if ($assets) {
                        return Result::fastReturn(['code' => 1, 'msg' => '', 'result' => $assets]);
                    } else {
                        return Result::fail('加载失败');
                    }
                case "save":
                    try {
                        $this->validate($param, 'Recharge');
                    } catch (ValidateException $e) {
                        return Result::fail($e->getError());
                    }
                    return Result::fastReturn($this->model::recharge($param, $this->admin));
                default:
                    return Result::fail('加载失败');
            }
        }
        View::assign('assets', Assets::getFields(3));

        return View::fetch();
    }
}